package com.jumi.microservice.api;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jumi.microservice.constant.ExceptionEnum;
import com.jumi.microservice.constant.StatusEnum;
import com.jumi.microservice.constant.UserAccountEnum;
import com.jumi.microservice.domain.Account;
import com.jumi.microservice.domain.temp.DepartmentTemp;
import com.jumi.microservice.mapper.AccountMapper;
import com.jumi.microservice.mapper.DepartmentMapper;
import com.jumi.microservice.service.IAccountService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 */
@Service
public class AccountApiImpl implements IAccountService {

    /**
     * 账号管理mapper组件
     */
    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public Map<Long, String> getAccountNamesByIds(List<Long> uids) {
        Map<Long, String> accountNameMap = new HashMap<>();
        for (Long uid : uids) {
            LambdaQueryWrapper<Account> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(Account::getIsDel, StatusEnum.STATUS_NO.getCode());
            wrapper.eq(uid != null, Account::getUid, uid);
            Account account = accountMapper.selectOne(wrapper);
            accountNameMap.put(uid, account.getUserName());
        }
        return accountNameMap;
    }

    /**
     * 根据用户获取 部门父级信息
     * @param uid 登录用户uid
     * @return
     */
    @Override
    public Map<String,Object> getAccountDepartment(Long uid) {
        Map<String,Object> map = new HashMap<>();
        StringBuilder sb = new StringBuilder();
        Account account = accountMapper.selectOne(
                Wrappers.<Account>lambdaQuery()
                        .eq(Account::getUid,uid));
        UserAccountEnum.USER_NOT_EXISTED.doThrowIf(account==null);
        //获取无线上级部门
        List<DepartmentTemp> list = departmentMapper.selectParentDep(account.getDepartmentId());
        list.stream().forEach(d->{
            sb.append(d.getDepartmentName());
            //不为最后低级部门继续添加 ->
            if(list.indexOf(d)!=list.size()-1) {
                sb.append("->");
            }
        });
        map.put("department", sb.toString());
        map.put("phone", account.getMobile());
        return map;
    }
}
